<script setup>
import { ref, onMounted, watch } from "vue";
import { ElTable, ElTableColumn } from "element-plus";
import Sortable from "sortablejs";

const props = defineProps({
  data: {
    type: Array,
    required: true,
  },
  loading: {
    type: Boolean,
    default: false,
  },
  canDrag: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:data"]);
const tableRef = ref(null);
let sortableInstance = null;

onMounted(() => {
  if (tableRef.value) {
    const tbody = tableRef.value.$el.querySelector("tbody");
    sortableInstance = new Sortable(tbody, {
      animation: 150,
      handle: ".el-table__row",
      ghostClass: "sortable-ghost",
      disabled: !props.canDrag,
      onEnd: (evt) => {
        const oldIndex = evt.oldIndex;
        const newIndex = evt.newIndex;
        const newData = [...props.data];
        const movedItem = newData[oldIndex];

        newData.splice(oldIndex, 1);
        newData.splice(newIndex, 0, movedItem);
        emit("update:data", newData);
      },
    });
  }
});

// 监听 canDrag 变化
watch(
  () => props.canDrag,
  (newValue) => {
    if (sortableInstance) {
      sortableInstance.option("disabled", !newValue);
    }
  }
);
</script>

<template>
  <el-table
    ref="tableRef"
    :data="props.data"
    style="width: 100%"
    :header-cell-style="{ background: '#32c5ff', color: '#fff' }"
    height="236px"
    :loading="props.loading"
    row-key="questionId"
    size="large"
  >
    <!-- 题目id列 -->
    <el-table-column
      prop="questionId"
      label="题目id"
      width="180px"
    ></el-table-column>
    <!-- 题目标题列 -->
    <el-table-column prop="title" label="题目标题"></el-table-column>
    <!-- 题目难度列 -->
    <el-table-column prop="difficulty" label="题目难度" width="180px">
      <template #default="{ row }">
        <div v-if="row.difficulty === 1" style="color: #3ec8ff">简单</div>
        <div v-if="row.difficulty === 2" style="color: #fe7909">中等</div>
        <div v-if="row.difficulty === 3" style="color: #fd4c40">困难</div>
      </template>
    </el-table-column>
    <!-- 操作列 -->
    <el-table-column label="操作" width="80px">
      <template #default="{ row }">
        <el-button
          link
          type="danger"
          @click="$emit('delete-question', row.questionId)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped>
.sortable-ghost {
  background-color: #f0f2f5;
  opacity: 0.8;
}
/* 防止行被拖动时出现空白 */
.el-table__body-wrapper {
  user-select: none;
}

/* 调整拖拽占位符样式 */
.sortable-ghost {
  opacity: 0.8;
  background: #f5f7fa !important;
}

/* 隐藏默认的拖拽动画 */
.sortable-chosen {
  transition: none !important;
}
</style>